package com.laicunba.ext.web.controller.console;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.laicunba.ext.web.controller.BaseController;
import com.laicunba.service.QueryService;
import com.laicunba.util.ExcelUtil;

@Controller
@RequestMapping(value = "/console/ext")
public class ExcelToolController extends BaseController {

	@Autowired
	@Qualifier("queryServiceSlaveImpl")
	private QueryService queryService;

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@ResponseBody
	@RequestMapping(value = "/exportexcel.htm")
	public void exportExcel(@RequestParam("listId") String listId, String excelname, HttpServletRequest request, HttpServletResponse response, Integer rows, String order, String sort, String noCount) throws Exception {
		Map p = new HashMap();
		Iterator it = request.getParameterMap().keySet().iterator();
		while (it.hasNext()) {
			String key = (String) it.next();
			p.put(key, request.getParameter(key));
		}
		QueryService.Parameter parameter = new QueryService.Parameter();

		parameter.setSqlId(listId);
		parameter.setMap(p);
		parameter.setPageNumber(1);
		parameter.setPageSize(rows == null ? 10 : rows);
		parameter.setSort(sort);
		parameter.setOrder(order);
		parameter.addAttribute("sort", sort);
		parameter.addAttribute("order", order);
		List<Map<String, Object>> jsonlist = queryService.list(parameter);
		if (jsonlist != null || jsonlist.size() > 0) {
			ByteArrayOutputStream stream = ExcelUtil.generate(jsonlist);
			// 将文件存到指定位置
			OutputStream fOut = null;
			response.setContentType("application/vnd.ms-excel");
			try {
				response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(excelname, "UTF-8") + ".xls");
				fOut = response.getOutputStream();
				fOut.write(stream.toByteArray());
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					fOut.flush();
					fOut.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
